package org.jeecgframework.core.util;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.web.system.pojo.base.DynamicDataSourceEntity;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Spring JDBC 瀹炴椂鏁版嵁搴撹闂�
 * 
 * @author chenguobin
 * @date 2014-09-05
 * @version 1.0
 */
public class DynamicDBUtil {
	private static final Logger logger = Logger.getLogger(DynamicDBUtil.class);
	private static JdbcTemplate jdbcTemplate;
	private static String dbName;
	/**20161209*/
	private static Map<String,JdbcTemplate> jdbcTemplateMap =new HashMap<String, JdbcTemplate>();
	
//	private static BasicDataSource getDataSource(final DynamicDataSourceEntity dynamicSourceEntity) {
//		BasicDataSource dataSource = new BasicDataSource();
//		String driverClassName = dynamicSourceEntity.getDriverClass();
//		String url = dynamicSourceEntity.getUrl();
//		String dbUser = dynamicSourceEntity.getDbUser();
//		String dbPassword = dynamicSourceEntity.getDbPassword();
//		
//		dataSource.setDriverClassName(driverClassName);
//		dataSource.setUrl(url);
//		dataSource.setUsername(dbUser);
//		dataSource.setPassword(dbPassword);
//		return dataSource;
//	}
	public static BasicDataSource getDataSource(final DynamicDataSourceEntity dynamicSourceEntity) {
		BasicDataSource dataSource = new BasicDataSource();
		String driverClassName = dynamicSourceEntity.getDriverClass();
		String url = dynamicSourceEntity.getUrl();
		String dbUser = dynamicSourceEntity.getDbUser();
		String dbPassword = dynamicSourceEntity.getDbPassword();
		
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(url);
		dataSource.setUsername(dbUser);
		dataSource.setPassword(dbPassword);
		return dataSource;
	}
	
	private static JdbcTemplate getJdbcTemplate(String dbKey) {
		DynamicDataSourceEntity dynamicSourceEntity = DynamicDataSourceEntity.DynamicDataSourceMap.get(dbKey);
		BasicDataSource dataSource = getDataSource(dynamicSourceEntity);
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); 
		return jdbcTemplate;
	}
	
	
	/**20161209
	 * */
    public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

    /**20161209
     * 鍒濆鍖朖dbcTemplate 瀵硅薄
     * */
	public static void setJdbcTemplate(String dbKey) {
		if(dbName==null||
				(dbName!=null&&!dbName.equals(dbKey))
				){
			dbName=dbKey;
			if(jdbcTemplate!=null){
				jdbcTemplate=null;
			}
			if(
					jdbcTemplateMap==null||
					jdbcTemplateMap.isEmpty()||!jdbcTemplateMap.containsKey(dbKey)){
				DynamicDataSourceEntity dynamicSourceEntity = DynamicDataSourceEntity.DynamicDataSourceMap.get(dbKey);
				BasicDataSource dataSource = getDataSource(dynamicSourceEntity);
				dbName=dbKey;
				jdbcTemplateMap.put(dbKey, new JdbcTemplate(dataSource));
			}
			jdbcTemplate = jdbcTemplateMap.get(dbKey);
		}
	}

	/**
	 * 璇ユ柟娉曞彧鏄柟渚跨敤浜巑ain鏂规硶娴嬭瘯璋冪敤
	 * @param dynamicSourceEntity
	 * @return JdbcTemplate
	 */
	private static JdbcTemplate getJdbcTemplate(DynamicDataSourceEntity dynamicSourceEntity) {
		BasicDataSource dataSource = getDataSource(dynamicSourceEntity);
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); 
		return jdbcTemplate;
	}
	
	/**
     * Executes the SQL statement in this <code>PreparedStatement</code> object,
     * which must be an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, <code>UPDATE</code> or
     * <code>DELETE</code>; or an SQL statement that returns nothing,
     * such as a DDL statement.
     */
	public static int update(final String dbKey, String sql, Object... param)
	{
		int effectCount = 0;
		JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);

		if (ArrayUtils.isEmpty(param)) {
			effectCount = jdbcTemplate.update(sql);
		} else {
			effectCount = jdbcTemplate.update(sql, param);
		}
		
		return effectCount;
	}
	
	public static Object findOne(final String dbKey, String sql, Object... param) {
		List<Map<String, Object>> list;
		JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);
		
		if (ArrayUtils.isEmpty(param)) {
			list = jdbcTemplate.queryForList(sql);
		} else {
			list = jdbcTemplate.queryForList(sql, param);
		}
		
		if(ListUtils.isNullOrEmpty(list))
		{
			logger.error("Except one, but not find actually");
		}
		
		if(list.size() > 1)
		{
			logger.error("Except one, but more than one actually");
		}
		
		return list.get(0);
	}
	/**20161209
	 * @return Map<String,Object>
	 * */
	public static Map<String,Object> getOne(final String dbKey, String sql, Object... param) {
		List<Map<String, Object>> list;
		setJdbcTemplate(dbKey);
		if (ArrayUtils.isEmpty(param)) {
			list = jdbcTemplate.queryForList(sql);
		} else {
			list = jdbcTemplate.queryForList(sql, param);
		}
		
		if(ListUtils.isNullOrEmpty(list))
		{
			logger.error("Except one, but not find actually");
		}
		
		if(list.size() > 1)
		{
			logger.error("Except one, but more than one actually");
			
		}
		if(list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
		
		
	}
	

	
	public static  List<Map<String,Object>> getList(final String dbKey, String sql, Object... param){
		List<Map<String, Object>> list;
		setJdbcTemplate(dbKey);
		if (ArrayUtils.isEmpty(param)) {
			list = jdbcTemplate.queryForList(sql);
		} else {
			list = jdbcTemplate.queryForList(sql, param);
		}
		
		return list;
	}
	public static List<Map<String, Object>> findList(final String dbKey, String sql, Object... param) {
		List<Map<String, Object>> list;
		JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);
		
		if (ArrayUtils.isEmpty(param)) {
			list = jdbcTemplate.queryForList(sql);
		} else {
			list = jdbcTemplate.queryForList(sql, param);
		}
		
		return list;
	}
	public static List<Map<String, Object>> findList(JdbcTemplate jdbcTemplate, String sql, Object... param) {
		List<Map<String, Object>> list;
		//JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);
		
		if (ArrayUtils.isEmpty(param)) {
			list = jdbcTemplate.queryForList(sql);
		} else {
			list = jdbcTemplate.queryForList(sql, param);
		}
		
		return list;
	}
	//add-begin--Author:luobaoli  Date:20150620 for锛氬鍔犺繑鍥炲�间负List鐨勬柟娉�
	public static <T> List<T> findList(final String dbKey, String sql, Class<T> clazz,Object... param) {
		List<T> list;
		JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey);
		
		if (ArrayUtils.isEmpty(param)) {
			list = jdbcTemplate.queryForList(sql,clazz);
		} else {
			list = jdbcTemplate.queryForList(sql,clazz,param);
		}
		return list;
	}
	//add-end--Author:luobaoli  Date:20150620 for锛氬鍔犺繑鍥炲�间负List鐨勬柟娉�
		
	public static void main(String[] args) {
		DynamicDataSourceEntity dynamicSourceEntity = new DynamicDataSourceEntity();
		
		String dbKey = "erp";
		String driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		String url = "jdbc:sqlserver://192.168.6.200:1433;DatabaseName=AIS20170901074346";
		String dbUser = "upbomwise";
		String dbPassword = "upbomwise";
		
		dynamicSourceEntity.setDbKey(dbKey);
		dynamicSourceEntity.setDriverClass(driverClassName);
		dynamicSourceEntity.setUrl(url);
		dynamicSourceEntity.setDbUser(dbUser);
		dynamicSourceEntity.setDbPassword(dbPassword);
		
		JdbcTemplate jdbcTemplate = getJdbcTemplate(dynamicSourceEntity);
		
		String sql = "select t_Base_Emp.FItemID,t_Base_Emp.FName basename ,t_Base_Emp.FNumber from t_Base_Emp ";
		List<Map<String, Object>> list = DynamicDBUtil.findList(jdbcTemplate, sql);
		System.out.println(list.size());
	}

	//=====================20170303===========================
	/**20161227
	 * 鏇存柊鏁版嵁
	 * */
	public static int updateBySQL(final String dbKey, String sql, Object... param)
	{
		int effectCount = 0;
		setJdbcTemplate(dbKey);
		if (ArrayUtils.isEmpty(param)) {
			effectCount = jdbcTemplate.update(sql);
		} else {
			effectCount = jdbcTemplate.update(sql, param);
		}
		return effectCount;
	}
	
}
